package com.bjsxt.ssm.service.impl;

import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bjsxt.ssm.bean.TbUserRole;
import com.bjsxt.ssm.mapper.TbUserRoleMapper;
import com.bjsxt.ssm.service.TbUserRoleService;


@Service
public class TbUserRoleServiceImpl implements TbUserRoleService {

	
	@Autowired
	private TbUserRoleMapper tbUserRoleMapper;
	
//	@Autowired
//	private TbUserMapper tbUserMapper ;

	@Override
	public int saveTbUserRole(Integer[] userIds) {
		if(null==userIds){
			return -1;
		}
		
		
		this.tbUserRoleMapper.insertTbUserRole(userIds);
		return userIds.length;
	}

	@Override
	public int useAppendRole(Integer[] userIds, Integer[] roleIds) {
		if(ArrayUtils.isEmpty(userIds)||ArrayUtils.isEmpty(roleIds)){
			return -1;
		}
		for (Integer userId : userIds) {
			for (Integer roleId : roleIds) {
				 TbUserRole userRole = new TbUserRole() ;
				 userRole.setRoleId(roleId);
				 userRole.setUserId(userId);
				int has =tbUserRoleMapper.checkTbUserRole(userRole);
				if(0 == has){
					tbUserRoleMapper.insertTbUserRole(userRole);
				}
			}
			
		}
				return 1;
	}

	@Override
	public int useOverWriteRole(Integer[] userIds, Integer[] roleIds) {
		
		if(ArrayUtils.isEmpty(userIds) || ArrayUtils.isEmpty(roleIds) ){
			return -1 ;
		}
		for (Integer userId : userIds) {
			 int r = tbUserRoleMapper.deleteTbUserRole(userId) ;
			 for (Integer roleId : roleIds) {
				TbUserRole userRole = new TbUserRole() ;
				
				userRole.setUserId(userId);
				userRole.setRoleId(roleId);
				tbUserRoleMapper.insertTbUserRole(userRole); 
			}
		}
		
		
		return 1;
	}

	@Override
	public List<TbUserRole> selectTbRoleByUserId(Integer userId) {
		if(null==userId){
			return null;
		}
		return this.tbUserRoleMapper.selectTbRoleByUserId(userId);
	}

}
